<?php namespace App\Services\TypesService;
/**
 * 后台主题
 *
 * 后台主题Service
 *
 * @author    zhouchao <zhouchao@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */
use App\Services\BaseService;
use App\Services\ImgServices\ImgTool;
use App\Services\ProductsService\ProductsBackService;
use App\Services\UserService\UserBackstage;
use App\Services\ProductTempService\ProductTempTool;
use DB;

class TypesBackService extends BaseService{

    protected $product_back_service;
    protected $user_backstage;
    public function __construct(ImgTool $img_tool,ProductsBackService $product_back_service,UserBackstage $user_backstage,ProductTempTool $productTempTool)
    {
        $this->img_tool = $img_tool;
        $this->product_back_service = $product_back_service;
        $this->user_backstage = $user_backstage;
        $this->productTempTool = $productTempTool;
    }

    /**
     * 根据一组id获取类型
     * @param $resource_ids
     * @return array
     */
    public function getListByReSourceIds($resource_ids){
        $this->table = 'types';
        $this->select = array('type_id','type_name','type_image','app_id','is_features');
        $types = array();
        foreach($resource_ids as $resource_id){
            if(is_object($resource_id)){
                $this->where = array(array('type_id','=',$resource_id->resource_id),array('is_show','=',1),array('state','=',1));
            }else{
                $this->where = array(array('type_id','=',$resource_id),array('is_show','=',1),array('state','=',1));
            }
            $type = $this->getById();
            if(!empty($type)){
                $types[] = $type;
            }
        }
        return $types;
    }

    /**
     * 获取主题列表
     * @param int $per_page
     * @return mixed
     */
    public function getList($per_page = 10)
    {
        $this->setParameter([
            'table' => 'types',
            'where' => [['state','=',1]],
            'select'=> ['type_id','type_name','type_image','app_id','is_show','sort','is_features','updated_at'],
            'order' => 'sort',
            'sort'  => 'desc'
        ]);
        $types = $this->getAllPaginated($per_page);
        foreach($types as $type){
            $type->type_image = $this->setImagePath($type->type_image);
        }
        return $types;
    }

    /**
     * 根据ID获取主题
     * @param $type_id
     * @return mixed
     */
    public function get_type_by_type_id($type_id){
        $this->setParameter([
            'table' => 'types',
            'where' => [['type_id','=',$type_id],['state','=',1]],
            'select'=> ['type_id','type_name','type_image','app_id','is_show','sort','is_features','updated_at']
        ]);
        $type = $this->getById();
        if(!empty($type)){
            $type->type_image = $this->setImagePath($type->type_image);
        }
        return $type;
    }

    /**
     * 修改主题状态
     * @param $type_id
     * @return mixed
     */
    public function update_type_state($type_id)
    {
        $this->setParameter(['table'=>'types','where'=>[['type_id','=',$type_id]],['state','=',1]]);
        return $this->update(array('state'=>2,'updated_at'=>time()));
    }

    /**
     * 修改主题排序
     * @param $type_id
     * @param $sort
     * @return mixed
     */
    public function update_type_sort($type_id,$sort){
        $this->setParameter(['table'=>'types','where'=>[['type_id','=',$type_id]],['state','=',1]]);
        return $this->update(array('sort'=>$sort,'updated_at'=>time()));
    }

    /**
     * 添加主题
     * @param $data
     * @return array
     */
    public function add_type($data){
        $update_data['type_name'] = trim($data['type_name']);
        $update_data['type_image'] = $this->img_tool->imgSave($data['type_image'],2);
        if(empty($update_data['type_image'])){
            return false;
        }
        $update_data['is_features'] = $data['is_features'];
        $update_data['app_id'] = $data['app_id'];
        $update_data['is_show'] = $data['is_show'];
        $update_data['created_at'] = $update_data['updated_at'] = time();
        return DB::table('types')->insertGetId($update_data);
    }

    /**
     * 修改主题
     * @param $data
     * @return bool
     */
    public function update_type($data){
        if(!empty($data['type_image'])){
            $data['type_image'] = $this->img_tool->imgSave($data['type_image'],2);
            if(empty($data['type_image'])){
                return false;
            }
        }
        $data['type_name'] = trim($data['type_name']);
        $data['updated_at'] = time();
        $this->table = 'types';
        $this->where = [['type_id','=',$data['type_id']]];
        return $this->update($data);
    }

    /**
     * 修改显示状态
     * @param $type_id
     * @param $is_show
     * @return mixed
     */
    public function change_type_show($type_id,$is_show){
        $this->setParameter(['table'=>'types','where'=>[['type_id','=',$type_id]],['state','=',1]]);
        return $this->update(array('is_show'=>$is_show,'updated_at'=>time()));
    }

    public function save_product_ids($product_ids,$type_id)
    {
        foreach($product_ids as $product_id){
            $type_resource = DB::table('type_resources')->where(['resource_id'=>$product_id,'type_id'=>$type_id])->first();
            if(empty($type_resource)){
                DB::table('type_resources')->insert(array('type_id'=>$type_id,'resource_id'=>$product_id,'created_at'=>time(),'updated_at'=>time()));
            }else{
                if($type_resource->state == 2){
                    DB::table('type_resources')->where(['resource_id'=>$product_id,'type_id'=>$type_id])->update(array('state'=>1,'updated_at'=>time()));
                }
            }
        }
    }

    public function delete_type_product($type_id,$product_id){
        $type_resource = DB::table('type_resources')->where(['resource_id'=>$product_id,'type_id'=>$type_id])->first();
        if(empty($type_resource)){
            return true;
        }
        return DB::table('type_resources')->where(['resource_id'=>$product_id,'type_id'=>$type_id])->update(array('state'=>2,'updated_at'=>time()));
    }

    public function get_search_product_list($search)
    {
        if(isset($search['product_temp_category_id']) && $search['product_temp_category_id'] != 0){
            $category_product_ids = $this->get_temp_ids($search['product_temp_category_id']);
            $this->whereIn = $category_product_ids;
        }
        if($search['user_type'] === '0' && $search['brand_id'] === '0' && $search['is_shelves'] === '-1' && empty($search['user_param']) && empty($search['product_id'])){
            $products = $this->get_products($search);
            return $products;
        }else{
            $product_ids_arr = array();
            if(isset($search['product_id']) && !empty($search['product_id'])){
                $product_ids_arr = array_merge($product_ids_arr,array($search['product_id']));
            }
            if(isset($search['user_type']) && $search['user_type'] !== '0'){
                $user_ids = $this->user_backstage->get_user_id_list($search['user_type'])->toArray();
                $product_ids = $this->product_back_service->get_products_by_ids('user_id',$user_ids)->toArray();
                if(empty($product_ids_arr)){
                    $product_ids_arr = array_merge($product_ids_arr,$product_ids);
                }else{
                    $product_ids_arr = array_intersect($product_ids_arr,$product_ids);
                }
            }
            if(isset($search['brand_id']) && $search['brand_id'] !== '0'){
                $product_temp_ids=DB::table('product_temps')->where(array('state'=>1))
                    ->where('brand_id',$search['brand_id'])
                    ->pluck('product_temp_id')
                    ->toArray();
                $product_ids = $this->product_back_service->get_products_by_ids('product_temp_id',$product_temp_ids)->toArray();
                if(empty($product_ids_arr)){
                    $product_ids_arr = array_merge($product_ids_arr,$product_ids);
                }else{
                    $product_ids_arr = array_intersect($product_ids_arr,$product_ids);
                }
            }
            if(isset($search['is_shelves']) && $search['is_shelves'] !== '-1'){
                $product_ids = $this->product_back_service->get_shelves_product($search['is_shelves'])->toArray();
                if(empty($product_ids_arr)){
                    $product_ids_arr = array_merge($product_ids_arr,$product_ids);
                }else{
                    $product_ids_arr = array_intersect($product_ids_arr,$product_ids);
                }
            }
            if(isset($search['user_param']) && !empty($search['user_param'])){
                $user_ids = DB::table('users')
                    ->where('nick_name','like','%'.$search['user_param'].'%')
                    ->orWhere('phone','like','%'.$search['user_param'].'%')
                    ->pluck('user_id')
                    ->toArray();
                $product_ids = $this->product_back_service->get_products_by_ids('user_id',$user_ids)->toArray();
                if(empty($product_ids_arr)){
                    $product_ids_arr = array_merge($product_ids_arr,$product_ids);
                }else{
                    $product_ids_arr = array_intersect($product_ids_arr,$product_ids);
                }
            }
            if(isset($search['product_temp_category_id']) && $search['product_temp_category_id'] != 0 && isset($category_product_ids)){
                $product_ids_arr = array_intersect($product_ids_arr,$category_product_ids);
            }
            $product_ids_arr = array_unique($product_ids_arr);
            $products = DB::table('products')
                ->where('state',1)
                ->whereIn('product_id',$product_ids_arr)
                ->select('product_id', 'user_id', 'colour_id', 'product_temp_id','overflow_price',
                    'title', 'description', 'dig_num', 'collect_num','is_shelves','off_shelves_time',
                    'is_infinite_time','remarks','sell_num','stock','is_infinite_stock','channel','is_show','updated_at','created_at')
                ->orderBy('updated_at','desc')
                ->paginate(10);
            //$products = DB::table('products')->where('state',1)->whereIn('product_id',$product_ids_arr)->select('product_id')->get()->toArray();
            foreach($products as $product){
                $this->product_back_service->get_product_preview_images($product);
                if(count($product->thumbnail) > 0){
                    $product->thumbnail_image = $product->thumbnail[0];
                }else{
                    $product->thumbnail_image = '';
                }
                $product->channel_name = array_search($product->channel,config('fashion.channel'));
            }
            return $products;
        }
    }

    public function get_temp_ids($product_temp_category_id){
        $product_temp_ids = $this->productTempTool->getAllProductTempIdsByCategoryId(intval($product_temp_category_id));
        //根据模板获取产品
        return DB::table('products')->whereIn('product_temp_id',$product_temp_ids)->where('state',1)->pluck('product_id')->toArray();
    }

    public function get_products($search){
        $this->setParameter([
            'table' => 'products',
            'where' => [['state','=',1]],
            'select'=> ['product_id', 'user_id', 'colour_id', 'product_temp_id','overflow_price',
                'title', 'description', 'dig_num', 'collect_num','is_shelves','off_shelves_time',
                'is_infinite_time','remarks','sell_num','stock','is_infinite_stock','channel','is_show','updated_at','created_at'],
            'order'=>'updated_at',
            'sort' =>'desc'    
        ]);
        if(isset($search['product_temp_category_id']) && $search['product_temp_category_id'] != 0){
            //$products = $this->getAllByResourceIds('product_id');
            $products = $this->getAllByResourceIdsPaginated('product_id',10);
        }else{
            //$products = DB::table('products')->where('state',1)->select('product_id')->get()->toArray();
            $products = DB::table('products')
                ->where('state',1)
                ->select('product_id', 'user_id', 'colour_id', 'product_temp_id','overflow_price',
                    'title', 'description', 'dig_num', 'collect_num','is_shelves','off_shelves_time',
                    'is_infinite_time','remarks','sell_num','stock','is_infinite_stock','channel',
                    'is_show','updated_at','created_at')
                ->orderBy('updated_at','desc')
                ->paginate(10);
        }
        foreach($products as $product){
            $this->product_back_service->get_product_preview_images($product);
            if(count($product->thumbnail) > 0){
                $product->thumbnail_image = $product->thumbnail[0];
            }else{
                $product->thumbnail_image = '';
            }
            $product->channel_name = array_search($product->channel,config('fashion.channel'));
        }
        return $products;
    }

    /**
     * 根据主题ID获取产品
     * @param $type_id
     */
    public function get_product_list_by_type_id($type_id,$per_page=10){
        $products = DB::table('type_resources')->where(['type_id'=>$type_id,'state'=>1])->orderBy('sort','desc')->paginate($per_page);
        foreach($products as $key=>$resource){
            $product = DB::table('products')->where('state',1)->where('product_id',$resource->resource_id)->select('product_id','is_shelves','is_show')->first();
            if(empty($product)){
                unset($products[$key]);
                continue;
            }
            $this->product_back_service->get_product_preview_images($product);
            if(count($product->thumbnail) > 0){
                $product->thumbnail_image = $product->thumbnail[0];
            }else{
                $product->thumbnail_image = '';
            }
            $resource->product = $product;
        }
        return $products;
    }

    /**
     * 修改主题产品排序
     * @param $type_id
     * @param $product_id
     * @param $sort
     * @return mixed
     */
    public function update_type_product_sort($type_id,$product_id,$sort){
        return DB::table('type_resources')->where(['type_id'=>$type_id,'resource_id'=>$product_id])->update(['sort'=>$sort,'updated_at'=>time()]);
    }
}